package com.yunfinal.api.tpl.template;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * Shared Method 扩展
 * @author  杜福忠
 */
public class TemplateFn extends StrKit {

    public boolean eq(Object a, Object b){
        if(Objects.equals(a, b)){
            return true;
        }
        return a != null && b != null && a.toString().equals(b.toString());
    }

    public boolean notEq(Object a, Object b){
        return !eq(a, b);
    }

    public String toJson(Object obj){
        return JsonKit.toJson(obj);
    }

    public Date now(){
        return new Date();
    }

    public boolean contains(String str, String s) {
        return StrKit.notBlank(str, s) && str.contains(s);
    }

    /**
     * 方便模板中 Record/Map/Controller对象赋值后，不输出任何内容，如：
     * #(set(x, "name", r.name))
     */
    public void set(Object obj, String column, Object value){
        if(obj instanceof Record){
            ((Record)obj).set(column, value);
            return;
        }
        if(obj instanceof Map){
            ((Map<Object,Object>)obj).put(column, value);
            return;
        }
        if (obj instanceof Controller){
            ((Controller)obj).setAttr(column, value);
            return;
        }
    }

    /**
     * 和 obj.compareTo(BigDecimal.ZERO) 比较
     * @param obj 和 0 比较的对象
     * @return =0代表等0，=1代表大于0，=-1代表小于0
     */
    public int compareToZERO(Object obj){
        if (obj == null){
            return 0;
        }
        if (obj instanceof BigDecimal){
            return ((BigDecimal)obj).compareTo(BigDecimal.ZERO);
        }
        if (obj instanceof Integer){
            return new BigDecimal((Integer)obj).compareTo(BigDecimal.ZERO);
        }
        if (obj instanceof Double){
            return new BigDecimal((Double)obj).compareTo(BigDecimal.ZERO);
        }
        return new BigDecimal(obj.toString()).compareTo(BigDecimal.ZERO);
    }
    
    


}
